import pygame
from pygame.sprite import Sprite
import random


class Alien(Sprite):

    def __init__(self, sw_setting, screen):
        super().__init__()
        self.screen = screen
        self.sw_setting = sw_setting

        self.image = pygame.image.load("../images/aline_ship.png")
        self.rect = self.image.get_rect()
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height
        self.x = float(self.rect.x)
        self.y = float(self.rect.y)
        dir_ary = [1, -1]
        # 1向右移动， -1像左
        self.fleet_lr_direction = random.choice(dir_ary)
        # 1向下移动， -1像上
        self.fleet_ud_direction = random.choice(dir_ary)

    def show_and_update(self):
        self.screen.blit(self.image, self.rect)

    def move(self):
        self.check_edge()
        self.check_move_area()
        self.x += self.sw_setting.alien_LR_speed_factor * self.fleet_lr_direction
        self.y += self.sw_setting.alien_UD_speed_factor * self.fleet_ud_direction
        self.rect.x = self.x
        self.rect.y = self.y

    # 检查左右是否越界
    def check_edge(self):
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right:
            self.fleet_lr_direction = -1
        elif self.rect.left <= 0:
            self.fleet_lr_direction = 1

    # 检查上下是否在规定活动区域内
    def check_move_area(self):
        screen_rect = self.screen.get_rect()
        if self.rect.top <= self.rect.height:
            self.fleet_ud_direction = 1
        elif self.rect.bottom >= screen_rect.height:
            self.fleet_ud_direction = -1
